import asyncio
import ccxt
import ccxt.pro
import json


with open("../keys.json") as f:
    accounts = json.load(f)

proxies = {
    "http": "http://127.0.0.1:10809",
    "https": "http://127.0.0.1:10809",
}


def get_binance_future_mock_exchange() -> ccxt.binance:
    exchange_name = "binance"
    account = "demo1"
    # account = "prod"
    public_key = accounts[exchange_name][account]["public"]
    secret_key = accounts[exchange_name][account]["secret"]

    exchange = ccxt.binance(
        {
            "apiKey": public_key,
            "secret": secret_key,
            "timeout": 300000,
            "options": {
                "defaultType": "future",  # 确保连接到期货市场
                # 'portfolioMargin': True
            },
        }
    )
    exchange.https_proxy = proxies["https"]
    exchange.set_sandbox_mode(True)
    return exchange


def get_binance_portfolio_exchange() -> ccxt.binance:
    exchange_name = "binance"
    # account = "demo1"
    account = "prod"
    public_key = accounts[exchange_name][account]["public"]
    secret_key = accounts[exchange_name][account]["secret"]

    exchange = ccxt.binance(
        {
            "apiKey": public_key,
            "secret": secret_key,
            "timeout": 300000,
            "options": {
                # 'defaultType': 'future',
                "portfolioMargin": True
            },
        }
    )
    exchange.https_proxy = proxies["https"]
    return exchange


def get_async_binance_portfolio_exchange() -> ccxt.pro.binance:
    exchange_name = "binance"
    # account = "demo1"
    account = "prod"
    public_key = accounts[exchange_name][account]["public"]
    secret_key = accounts[exchange_name][account]["secret"]

    exchange = ccxt.pro.binance(
        {
            "apiKey": public_key,
            "secret": secret_key,
            "timeout": 300000,
            "https_proxy": proxies["https"],
            "options": {"defaultType": "margin", "portfolioMargin": True},
        }
    )
    # exchange.https_proxy = proxies["https"]
    exchange.ws_proxy = proxies["https"]
    return exchange


def test_binance_future_order():
    exchange = get_binance_portfolio_exchange()
    symbol = "ETH/USDT:USDT"
    # now_info = exchange.fetch_ticker(symbol)
    order_book = exchange.fetch_order_book(symbol)
    exchange.set_leverage(7, symbol)

    exchange.create_order(
        symbol,
        "limit",
        side="buy",
        amount=0.01,
        price=order_book["bids"][0][0] - 100,
        params={
            "timeInForce": "GTC",  # GTC, IOC, FOK
            "side": "long",
        },
    )
    exchange.create_order(
        symbol,
        "limit",
        side="sell",
        amount=0.01,
        price=order_book["asks"][0][0] + 10,
        params={"timeInForce": "GTC", "side": "short"},  # GTC, IOC, FOK
    )
    orders = exchange.fetch_orders(symbol)
    one_order = None
    for x in orders:
        if x["status"] == "open":
            one_order = x

    if one_order:
        exchange.cancel_order(one_order["id"], one_order["symbol"])


def test_watch_balance():
    exchange = get_async_binance_portfolio_exchange()
    print("start watching balance")
    while True:
        result = asyncio.get_event_loop().run_until_complete(exchange.watch_balance())
        print(result)


def test_watch_position():
    exchange = get_async_binance_portfolio_exchange()
    print("start watching position")
    while True:
        result = asyncio.get_event_loop().run_until_complete(
            exchange.watch_positions(["ETH/USDT:USDT", "BTC/USDT:USDT", "ETH/BTC:BTC"])
        )
        print(result)


# exchange.load_markets()


if __name__ == "__main__":
    test_binance_future_order()
    # test_watch_balance()
    # test_watch_position()
